package com.evil.DAO;

import com.evil.Bean.ShareBean;
import com.evil.DB_Utils.*;
import com.evil.DB_Utils.ErrorInfo;
import com.evil.Utils.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;

/********************************************
 * 工程名：Web
 * 包名：com.evil.DAO
 * 时间：16-9-25 下午10:00
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：分享邀请DAO
 ********************************************/
public class ShareDAO
{
    private static Logger log = Logger.getLogger(ShareDAO.class);
    private int times = 0;

    private String insert_inviter_re;
    private String inviteesJSON;
    private String inviter_phone2;

    /**
     * 登陆时插入，如果有该值直接报错并且忽略
     */
    public boolean insert(String phone)
    {
        final String url = "INSERT INTO `edasupport`.`share` "
                + "(`phone`) "
                + "VALUES (?);";

        String re = DB_Utils.insert(url).add(phone).build().close();

        if (re.equals(ErrorInfo.ERROR_EXIST_PRIMARY.toString()))
        {
            return false;
        }
        /*用户表没有该手机号，很少出现此情况*/
        else if (re.equals(ErrorInfo.ERROR_NO_FOREIGN_VALUE.toString()))
        {
            log.error(phone + ">>>用户表无该手机号！严重错误，紧急修复！！！"+"\r\n");
            return false;
        }
        else
        {
            times++;

            if (times >= 3)
                log.error(phone + "Share表插入失败"+"\r\n");
            else
                insert(phone);
        }
        return false;
    }

    /**
     * 插入邀请人
     */
    public String insert_inviter(String phone, String inviter_phone)
    {
        /*查询此用户是否已经填写*/
        final String user_query = "SELECT\n" +
                "`share`.inviter_phone,\n" +
                "`share`.inviter_time\n" +
                "FROM\n" +
                "`share`\n" +
                "WHERE\n" +
                "`share`.phone = ?";

        /*用户表更新邀请人*/
        final String user_update = "UPDATE `edasupport`.`share` SET "
                + "`inviter_phone`=?, "
                + "`inviter_time`=?"
                + "WHERE (`phone`=?);";

        /*邀请人查询被邀请人表，获得JSON转化为list，插入此用户的值后再转化为JSON重新更新表*/
        final String inviter_query = "SELECT\n" +
                "`share`.inviter_phone,\n" +
                "`share`.invitees\n" +
                "FROM\n" +
                "`share`\n" +
                "WHERE\n" +
                "`share`.phone = ?";

        /*邀请人表更新被邀请人*/
        final String inviter_update = "UPDATE `edasupport`.`share` SET "
                + "`invitees`=?"
                + "WHERE (`phone`=?);";


        /*先查询用户是否已经填写过邀请码*/
        DB_Utils.query(user_query).add(phone).build().get(next ->
        {
            if (next.next())
            {
                String ph = next.getString(1);
                String time = next.getDateTime(2);

                /*如果为空，则还未填写邀请码*/
                if (ph == null)
                {
                    /*先判断是否为相互邀请，如果不是则插入JSON，先查询JSON，转为list，然后add，最后加入数据库。之后更新用户的邀请人*/
                    DB_Utils.query(inviter_query).add(inviter_phone).build().get(next1 ->
                    {
                        if (next1.next())
                        {
                            inviter_phone2 = next1.getString(1);
                            inviteesJSON = next1.getString(2);
                        }
                    }).close();

                    /*如果相等，则为相互邀请，返回错误*/
                    if (inviter_phone2 != null && inviter_phone2.equals(phone))
                        insert_inviter_re = "ERROR:" + "请勿相互邀请！";
                    else
                    {
                        ArrayList<ShareBean.Invitee> list = new Gson().fromJson(inviteesJSON
                                , new TypeToken<ArrayList<ShareBean.Invitee>>()
                                {
                                }.getType());

                        if (list == null)
                            list = new ArrayList<ShareBean.Invitee>();

                        list.add(new ShareBean.Invitee(phone, new Date()));

                        Log.println(list.toString());
                        /*更新JSON*/
                        String re = DB_Utils.update(inviter_update).add(new Gson().toJson(list))
                                .add(inviter_phone).build().close();

                        /*更新用户的邀请人*/
                        String re2 = DB_Utils.update(user_update)
                                .add(inviter_phone).add(new Date())
                                .add(phone).build().close();

                        if (re.equals("1") && re2.equals("1"))
                            insert_inviter_re = "SUCCESS:" + "您的邀请人是" + inviter_phone + "。邀请码填写成功，流量次月将打入您的手机号中！";
                        else
                            insert_inviter_re = "FAIL:" + "您可能填写了错误的手机号码，或者该手机号码尚未注册，请您检查后重试。如果有任何疑问，请反馈手动提交给工作人员，感谢您的配合！";
                    }
                }
                /*已经填写邀请码，返回错误*/
                else
                    insert_inviter_re = "ERROR_OVER:您已经填写过邀请码，邀请您的用户是" + ph
                            + ",时间是" + time + ".\n欢迎您邀请其他用户，您也同时可以获得流量哦！";
            }
            /*如果为空,则无此主键，插入此用户，基本不使用*/
            else
                insert(phone);

        }).close();

        return insert_inviter_re;
    }


    /**
     * 获得所有被邀请人
     */
    public String getAll_invitees(String phone)
    {
        /*检测Share表是否存在->因为要进入分享页面，必定经过此函数*/
        insert(phone);

        inviteesJSON = "";

        final String url = "SELECT\n" +
                "`share`.phone,\n" +
                "`share`.invitees\n" +
                "FROM\n" +
                "`share`\n" +
                "WHERE\n" +
                "`share`.phone = ?";

        DB_Utils.query(url).add(phone).build().getAll(next ->
                inviteesJSON = next.getString(2)).close();

        return inviteesJSON;
    }

}
